import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/group_entity.dart';
import 'package:wanxiang_app/bean/group_list_entity.dart';
import 'package:wanxiang_app/bean/im_entity.dart';
import 'package:wanxiang_app/bean/msg_log_entity.dart';
import 'package:wanxiang_app/bean/msg_new_service_entity.dart';
import 'package:wanxiang_app/bean/service_list_entity.dart';
import 'package:wanxiang_app/bean/service_msg_list_entity.dart';
import 'package:wanxiang_app/bean/team_logos_entity.dart';
import 'package:wanxiang_app/bean/user_list_entity.dart';
import 'package:wanxiang_app/pages/home/tousu.dart';
import 'package:wanxiang_app/pages/msg/chat.dart';
import 'package:wanxiang_app/pages/msg/notice.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/tousu_entity.dart';
import '../../bean/user_list_entity.dart';
import '../../bean/user_list_entity.dart';
import '../../bean/user_list_entity.dart';
import '../../bean/user_list_entity.dart';
import '../../bean/user_list_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/tabChangeEvent.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:badges/badges.dart' as badges;
import 'package:bot_toast/bot_toast.dart';
import 'group.dart';
import 'msgDetail.dart';

class MsgController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    tabbarEventBus.on<TabChangedEvent>().listen((event) {
      if (event.tabIndex == 3) {
        _getServices();
        // _getStatus();
      }
    });

    // _getStatus();
    _getTousuList();
    _getMessageLog();
    _getServices();
    _getUnReadTotal();
  }

  @override
  void onClose() {
    super.onClose();
  }

  List itemList = [
    {'img': 'msg1.png', 'text': '平台客服'},
    {'img': 'msg2.png', 'text': '交易群组'},
    {'img': 'msg3.png', 'text': '系统消息'},
    {'img': 'msg4.png', 'text': '投诉客服'},
  ];
  int clickIndex = 0;
  List<ImData> UserListData = [];
  List<MsgNewServiceData> serviceList = [];
  List<NIMSession> sessions = [];
  List<NIMSession> singleSessions = [];
  List<NIMSession> groupSessions = [];
  List<GroupListEntity> groupList = [];

  int unReadNum = 0;
  int unReadTeamNum = 0;

  void _getUnReadTotal() async {
    // NIMResult<int> result =
    // await NimCore.instance.messageService.queryTotalUnreadCount(
    // );
    // unReadNum = result.data!;
    // update();
  }

  void _getStatus() {
    NimCore.instance.messageService
        .querySessionList(100)
        .then<NIMResult>((result) {
      if (result.isSuccess) {
        tabbarEventBus.fire(TabChangedEvent(100));
        unReadNum=0;
        unReadTeamNum=0;
        sessions = [];
        singleSessions=[];
        groupSessions=[];
        for (var item in result.data!) {
          if (item.sessionType == NIMSessionType.p2p) {
            unReadNum = unReadNum + item.unreadCount!.toInt();
            singleSessions.add(item);
          } else if (item.sessionType == NIMSessionType.team) {
            unReadTeamNum = unReadTeamNum + item.unreadCount!.toInt();
            groupSessions.add(item);
          }
        }
        List<String> ids = [];
        for (var item in sessions) {
          ids.add(item.sessionId);
        }
        sessions = singleSessions;
        for (int i = 0; i < sessions.length; i++) {
          for (var item in serviceList) {
            if (item.account == sessions[i].sessionId) {
              Map<String, dynamic> map = {};
              if (sessions[i].extension == null) {
                sessions[i].extension = map;
              } else {}
              sessions[i].extension?['nickname'] = item.nickname;
              sessions[i].extension?['photo'] = item.photo;
              sessions[i].extension?['account'] = item.account;
              sessions[i].extension?['isrest'] = item.isRest;
              break;
            }
          }
        }
        singleSessions = sessions;
        _grouplogos();
      } else {}
      return result;
    });
  }

  _grouplogos() {
    DioManager.getInstance().post(ServiceUrl.getImTeamLogo, {},
            (data) async {
              TeamLogosEntity bannerEntity = TeamLogosEntity.fromJson(jsonDecode(data));
              _groupMsg(bannerEntity.data);
        }, (error) {
          ToastUtil.show(error);
        });

  }

  _updateMsg(id) {
    DioManager.getInstance().post(ServiceUrl.getUpdateMessageLog, {
      'id':id
    },
            (data) async {
        }, (error) {
          ToastUtil.show(error);
        });

  }

  _groupMsg(List<TeamLogosData> logos) {
    NimCore.instance.teamService.queryTeamList().then((value) {
      if (value.isSuccess) {
       var  group = value.data!;
       groupList=[];
        for(var item in group){
          GroupListEntity groupListEntity = new GroupListEntity();
          groupListEntity.name = item.name!;
          groupListEntity.account = item.id!;
          groupList.add(groupListEntity);
        }
        for (int i = 0; i < groupList.length; i++) {
          bool has =false;
          String aa = groupList[i].name;
          for (var item in logos) {
            if(aa.startsWith("ZJ-")){
              List<String>  sss=aa.split('-');
              String bb = "";
              String dd = sss[1];
              for(int i=0;i<dd.length;i++){
                  if(dd[i].isNum){
                    break;
                  }else{
                    bb =bb+dd[i];
                  }
              }
              if(bb==item.anotherName){
                groupList[i].photo=item.zjLogo;
                has = true;
                break;
              }
            }
            else if(aa.contains(RegExp(replaceEmpty(item.name.toString())), 0)){
              if(item.name.startsWith("zj-")){
                groupList[i].photo=item.zjLogo;
              }else{
                groupList[i].photo=item.logo;
              }

              has = true;
              break;
            }
          }
          if(!has){
            groupList[i].photo='http://p.taohaoge.com/images/photo/20240703103403.png';
          }
        }
        for (int i = 0; i < groupList.length; i++) {
          for (var item in groupSessions) {
            groupList[i].lastmsg ='';
            groupList[i].time2 = item.lastMessageTime! ;
            groupList[i].time =  _getDate(item.lastMessageTime) ;
            if (item.sessionId == groupList[i].account) {
              groupList[i].unread =item.unreadCount!;
              groupList[i].lastmsg = item.lastMessageContent!;
              groupList[i].sessionId =item.sessionId;
              break;
            }
          }
        }

       var len = groupList.length;
       for (var i = 0; i < len; i++) {
         for (var j = 0; j < len - i - 1; j++) {
           if (groupList[j].time2 < groupList[j + 1].time2 ) {
             var tmp = groupList[j + 1];
             groupList[j + 1] = groupList[j];
             groupList[j] = tmp;
           }
         }
       }

        update();
      }
    });
  }

  String replaceEmpty(str){
    String aa = str.replaceAll(new RegExp(r"\s+\b|\b\s"), "");

    return aa;
  }

  String _getDate(timeStamp){
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timeStamp);
    var month = dateTime.month.toString();
    if(dateTime.month<10){
      month = '0${dateTime.month}';
    }
    return '${month}-${dateTime.day<10?'0${dateTime.day}':dateTime.day} ${dateTime.hour<10?'0${dateTime.hour}':dateTime.hour}:${dateTime.minute<10?'0${dateTime.minute}':dateTime.minute}';
  }
  void _getServices() {
    DioManager.getInstance().getRequest2(ServiceUrl.getImByAccount, {},
        (data) async {
      var parsedJson = json.decode(data);
      MsgNewServiceEntity bannerEntity =
          MsgNewServiceEntity.fromJson(jsonDecode(parsedJson));
      serviceList = bannerEntity.data;
      _getStatus();
      tabbarEventBus.fire(TabChangedEvent(100));
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }



  int msgLogPage = 1;
  List<MsgLogData> msgLogList = [];
  int messageLogUnread = 0;
  void _getMessageLog() {
    tabbarEventBus.fire(TabChangedEvent(100));
    DioManager.getInstance().post(ServiceUrl.getMessageLog, {
      "user_id": UserUtil.getUSER()?.id.toString(),
      "page": msgLogPage.toString(),
      "pagesize": "200"
    }, (data) async {
      print('==================');
      MsgLogEntity bannerEntity = MsgLogEntity.fromJson(jsonDecode(data));
      msgLogList=[];
      msgLogList.addAll(bannerEntity.data);
      messageLogUnread = 0;
      for (int i = 0; i < msgLogList.length; i++) {
        if(msgLogList[i].isRead!=1){
          messageLogUnread ++;
        }
      }

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  String? _getMsgContent(NIMSession session) {
    if (session.lastMessageType == NIMMessageType.text) {
      return session.lastMessageContent;
    }
    if (session.lastMessageType == NIMMessageType.image) {
      return '[图片]';
    }

    if (session.lastMessageType == NIMMessageType.custom) {
      return '[自定义消息]';
    }
    return '未知消息类型';
  }

  List<TousuData> touSulist = [];

  void _getTousuList() {
    DioManager.getInstance().post(ServiceUrl.tousu, null, (data) async {
      TousuEntity bannerEntity = TousuEntity.fromJson(jsonDecode(data));
      touSulist = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }



}

class MsgPage extends GetView<MsgController> {
  late MsgController controller;

  late BuildContext context;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<MsgController>(() => MsgController());
    controller = Get.find();
    context = context1;

    return GetBuilder<MsgController>(
      builder: (_) {
        return Scaffold(
            appBar: MyAppBar(context: context, title: '消息'),
            backgroundColor: Colors.white,
            body: _content());
      },
    );
  }

  Widget _content() {
    return Container(
      child: Column(
        children: [
          Container(
            height: 10.h,
            color: Color(0xFFF5F5F5),
          ),
          Container(
              padding: EdgeInsets.only(left: 14.w, right: 14.w, top: 12.h),
              child: _top()),
          SizedBox(
            height: 20.h,
          ),
          Row(
            children: [
              SizedBox(
                width: 20.w,
              ),
              Image.asset(
                Constant.IMG_BASE + 'item_new.png',
                width: 22.w,
                height: 18.h,
              ),
              SizedBox(
                width: 5.w,
              ),
              Text(controller.itemList[controller.clickIndex]['text'])
            ],
          ),
          controller.clickIndex == 0 ? _chatList() : Container(),
          controller.clickIndex == 1 ? _groupChatList() : Container(),
          controller.clickIndex == 2 ? _sysList() : Container(),
          controller.clickIndex == 3
              ? Column(
                  children: _tousuItems(),
                )
              : Container(),
        ],
      ),
    );
  }

  Widget _top() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _topItem('平台客服', 0),
        _topItem('交易群组', 1),
        _topItem('系统消息', 2),
        _topItem('投诉客服', 3),
      ],
    );
  }

  Widget _topItem(name, index) {
    var msgNBum = 0;
    if(index==0){
      msgNBum = controller.unReadNum;
    }
    if(index==1){
      msgNBum = controller.unReadTeamNum;
    }
    if(index==2){
      msgNBum = controller.messageLogUnread;
    }

    return InkWell(
        onTap: () {
          if (name == '平台客服') {
          } else if (name == '投诉客服') {
          } else if (name == '交易群组') {
          } else {}
          controller.clickIndex = index;
          controller.update();
        },
        child: controller.clickIndex == index
            ? _selected(
                Constant.IMG_BASE + controller.itemList[index]['img'], name,msgNBum)
            : _unSelected(Constant.IMG_BASE +controller.itemList[index]['img'], name,msgNBum));
  }


  List<Widget> _tousuItems() {
    List<Widget> aa = [];
    for (int i = 0; i < controller.touSulist.length; i++) {
      aa.add(_tousu(controller.touSulist[i]));
    }
    return aa;
  }

  Widget _tousu(item) {
    return Container(
      height: 238.h,
      alignment: Alignment.center,
      margin: EdgeInsets.all(16.h),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            Constant.IMG_BASE + 'tousu.png',
            width: 48.w,
            height: 48.h,
          ),
          SizedBox(
            height: 17.h,
          ),
          Text(item.title),
          SizedBox(
            height: 8.h,
          ),
          InkWell(
              onTap: () {
                Clipboard.setData(ClipboardData(text: item.content));
                ToastUtil.show('复制成功');
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(item.content),
                  SizedBox(
                    width: 5.w,
                  ),
                  Image.asset(
                    Constant.IMG_BASE + 'copy.png',
                    width: 9.w,
                    height: 9.h,
                  )
                ],
              ))
        ],
      ),
    );
  }

  Widget _sysInfoItem(MsgLogData item) {
    return InkWell(
      onTap: (){
        controller._updateMsg(item.id.toString());
        item.isRead = 1;
        BotToast.showLoading();
        Future.delayed(Duration(milliseconds: 500), () {
          BotToast.closeAllLoading();
          Get.to(() => MsgDetailPage(),
              arguments:item.remark,
              preventDuplicates: false)
              ?.then((value) => controller._getMessageLog());
        });

      },
      child: Container(
        margin: EdgeInsets.only(top: 15.w, left: 15.w, right: 15.w),
        padding: EdgeInsets.all(15.w),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.r),
            border: Border.all(color: Color(0xFFF3F3F3), width: 1.w)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                item.isRead==1?Container():
                Container(
                  width: 10.w,
                  height: 10.w,
                  alignment: Alignment.center,
                  decoration:
                  const BoxDecoration(shape: BoxShape.circle, color: Colors.red),
                ),
                Expanded(child: Text(
                  item.remark,
                  style: TextStyle(color: Color(0xFF333333), fontSize: 15.sp),
                ))
                // Text(
                //   item.remark,
                //   style: TextStyle(color: Color(0xFF333333), fontSize: 15.sp),
                // ),
              ],
            ),

            SizedBox(
              height: 5.h,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  Common.transferDate(item.time),
                  style: TextStyle(color: Color(0xFF999999), fontSize: 12.sp),
                )
              ],
            )
          ],
        ),
      )
    ) ;
  }

  Widget _selected(img, text,msgNum) {
    return msgNum>0?  badges.Badge(
        badgeContent: Text(
          msgNum.toString(),
          style:
          TextStyle(color: Colors.white, fontSize: 12.sp),
        ),
      child: _select2(img, text)
    ):_select2(img, text) ;
  }

  Widget _select2(img,text){
    return Container(
        width: 80.w,
        height: 92.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6.r),
            gradient: const LinearGradient(
              //渐变位置
                begin: Alignment.topCenter, //右上
                end: Alignment.bottomCenter, //左下
                stops: [
                  0.0,
                  1.0
                ], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [
                  Color.fromRGBO(165, 212, 254, 1),
                  Color.fromRGBO(3, 125, 230, 1)
                ])),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                width: 73.w,
                height: 25.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xFF389CF2),
                    borderRadius: BorderRadius.circular(13.r)),
                child: Text(
                  text,
                  style: TextStyle(color: Colors.white, fontSize: 12.sp),
                )),
            SizedBox(
              height: 16.h,
            ),
            Image.asset(
              img,
              width: 42.w,
              height: 42.h,
            ),
          ],
        ));
  }

  Widget _unSelected(img, text,msgNum) {
    print(img);

    return msgNum>0? badges.Badge(
        badgeContent: Text(
          msgNum.toString(),
          style:
          TextStyle(color: Colors.white, fontSize: 12.sp),
        ),
        child: _uuu( text,img,)
    ): _uuu(text, img);
  }


  Widget _uuu(text,img){
    return Container(
        width: 74.w,
        height: 84.h,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6.r),
            gradient: const LinearGradient(
              //渐变位置
                begin: Alignment.topCenter, //右上
                end: Alignment.bottomCenter, //左下
                stops: [
                  0.0,
                  1.0
                ], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [
                  Color.fromRGBO(236, 236, 236, 1),
                  Color.fromRGBO(197, 197, 197, 1)
                ])),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                width: 65.w,
                height: 23.h,
                alignment: Alignment.center,
                decoration:
                BoxDecoration(borderRadius: BorderRadius.circular(13.r),color: Color(0xffcecece)),
                child: Text(
                  text,
                  style: TextStyle(color: Colors.white, fontSize: 11.sp),
                )),
            SizedBox(
              height: 16.h,
            ),
            Image.asset(
             img,
              width: 41.w,
              height: 38.h,
            ),
          ],
        ));
  }

  Widget _chatList() {
    return Container(
        height: Get.height - 287.h,
        margin: EdgeInsets.only(bottom: 1.h),
        child: ListView.builder(
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _serviceItem(controller.sessions[index]); //每个item的布局
            },
            itemCount: controller.sessions.length));
  }

  Widget _groupChatList() {
    return Container(
        height: Get.height - 287.h,
        margin: EdgeInsets.only(bottom: 1.h),
        child: ListView.builder(
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _groupItem(controller.groupList[index]); //每个item的布局
            },
            itemCount: controller.groupList.length));
  }

  Widget _sysList() {
    return Container(
        height: Get.height - 287.h,
        margin: EdgeInsets.only(bottom: 1.h),
        child: ListView.builder(
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _sysInfoItem(controller.msgLogList[index]); //每个item的布局
            },
            itemCount: controller.msgLogList.length));
  }

  Widget _groupItem(GroupListEntity item) {
    return InkWell(
        onTap: () {
            BotToast.showLoading();
            Future.delayed(Duration(milliseconds: 500), () {
              BotToast.closeAllLoading();
              Get.to(() => GroupPage(),
                  arguments: {
                    'sessionId':item.account,
                    'nickName':item.name,
                    'servicePhoto':item.photo,
                    'account':item.account,
                  },
                  preventDuplicates: false)
                  ?.then((value) {
                controller._getStatus();
              } );
            });


        },
        child: Container(
          margin: EdgeInsets.only(left: 22.w, right: 22.w, top: 19.h),
          child: Row(
            children: [
              Row(
                children: [

                  Container(
                    width: 48.w,
                    height: 50.w,
                    child:   Stack(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 2.h),
                          child:  ClipOval(
                              child: CachedNetworkImage(
                                  imageUrl: item.photo,
                                  imageBuilder: (context, imageProvider) => Container(
                                      width: 48.w,
                                      height: 48.w,
                                      decoration: BoxDecoration(
                                        image: DecorationImage(
                                          image: imageProvider,
                                          fit: BoxFit.cover,
                                        ),
                                      ))))
                        )
                       ,

                        item.unread > 0
                            ? ClipOval(
                          child: Container(
                            alignment: Alignment.center,
                            width: 20.w,
                            height: 20.w,
                            color: Colors.redAccent,
                            child: Text(
                              item.unread.toString(),
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp),
                            ),
                          ),
                        )
                            : Container()

                      ],
                    )
                  ),
                  SizedBox(width: 5.w,),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                           Container(
                             width: Get.width - 180.w,
                              child:  Text(
                                '${item.name}',
                                overflow: TextOverflow.ellipsis, //长度溢出后显示省略号
                                style:  TextStyle(
                                  fontSize: 14.sp,
                                  color:  Color(0xFF333333),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          //
                          // Text('${item.name}',style: TextStyle(
                          //     color: Color(0xFF333333),
                          //     fontWeight: FontWeight.bold,
                          //     fontSize: 14.sp
                          // ),),
                          Text('${item.time}',style: TextStyle(
                              color: Color(0xFF333333),
                              fontWeight: FontWeight.bold,
                              fontSize: 14.sp
                          ),),
                        ],
                      ),
                      SizedBox(
                        height: 5.h,
                      ),
                      Container(
                        width: Get.width - 100.w,
                        child:  Text(

                          Common.msgFilter(item.lastmsg),
                          overflow: TextOverflow.ellipsis, //长度溢出后显示省略号
                          style:  TextStyle(
                            fontSize: 12.sp,
                            color:  Color(0xFF666666),
                          ),
                        ),
                      ),
                      // Text('${item.lastmsg}',style: TextStyle(
                      //     color: Color(0xFF666666),
                      //     fontSize: 12.sp
                      // )),
                      SizedBox(
                        height: 5.h,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  Widget _serviceItem(NIMSession item) {
    return InkWell(
        onTap: () {
          BotToast.showLoading();
          UserUtil.saveService(item.senderAccount!);
          Future.delayed(Duration(milliseconds: 500), () {
            BotToast.closeAllLoading();
            Get.to(() => ChatPage(),
                arguments: {
                  'sessionId': item.sessionId,
                  'nickName': item.extension?['nickname'],
                  'servicePhoto': Constant.IMG_NET_BASE+ item.extension?['photo'],
                  'online': item.extension?['isrest'],
                  'account':item.senderAccount
                },
                preventDuplicates: true)
                ?.then((value) => controller._getServices());
          });

        },
        child: item.extension == null
            ? Container()
            : Container(
                margin: EdgeInsets.only(left: 22.w, right: 22.w, top: 19.h),

                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        _offLine(item),
                        SizedBox(
                          width: 15.w,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text(
                                  '${item.extension?['nickname']}',
                                  style: TextStyle(
                                      color: Color(0xFF333333),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 14.sp),
                                ),
                                SizedBox(
                                  width: 2.w,
                                ),
                                Image.asset(
                                  Constant.IMG_BASE + 'gov.png',
                                  width: 26.w,
                                  height: 13.h,
                                ),
                                SizedBox(
                                  width: 10.w,
                                ),

                              ],
                            ),
                            // Text('${item.msg}',style: TextStyle(
                            //     color: Color(0xFF666666),
                            //     fontSize: 12.sp
                            // ),
                            SizedBox(
                              height: 5.h,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                    width: Get.width - 205.w,
                                    child: Text(
                                      '${controller._getMsgContent(item)}',
                                      style: TextStyle(
                                          color: item.unreadCount! > 0
                                              ? Colors.redAccent
                                              : Color(0xFF666666),
                                          fontSize: 12.sp),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      textAlign: TextAlign.left,
                                    )),

                                Text(controller. _getDate(item.lastMessageTime),style: TextStyle(
                                  color: Color(0xFF666666),
                                  fontSize: 12.sp
                                ),)
                              ],
                            )
                        ,
                          ],
                        ),
                      ],
                    ),
                    Image.asset(
                      Constant.IMG_BASE + 'msg_arrow_right.png',
                      width: 6.w,
                      height: 11.h,
                    )
                  ],
                ),
              ));
  }

  Widget _offLine(NIMSession item) {
    return Container(
        width: 50.w,
        height: 50.h,
        child: Stack(
          children: [
            Container(

              width: 48.w,
              height: 50.h,
              child: Stack(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 2.h),
                    child: ClipOval(
                        child: CachedNetworkImage(
                            imageUrl:
                            Constant.IMG_NET_BASE + item.extension?['photo'],
                            imageBuilder: (context, imageProvider) => Container(
                                width: 48.w,
                                height: 48.w,
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                    image: imageProvider,
                                    fit: BoxFit.cover,
                                  ),
                                ))))
                  )
                  ,
                  item.unreadCount! > 0
                      ? ClipOval(
                    child: Container(
                      alignment: Alignment.center,
                      width: 20.w,
                      height: 20.w,
                      color: Colors.redAccent,
                      child: Text(
                        item.unreadCount.toString(),
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 12.sp),
                      ),
                    ),
                  )
                      : Container()
                ],
              ),
            ),
            item.extension?['isrest'] == 0
                ? Positioned(
                    bottom: 0,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Color(0xFF08d408),
                          borderRadius: BorderRadius.circular(10.r)),
                      padding: EdgeInsets.fromLTRB(10.w, 1.h, 10.w, 1.h),
                      child: Row(
                        children: [
                          Image.asset(
                            Constant.IMG_BASE + 'on_line.png',
                            width: 8.w,
                            height: 8.w,
                          ),
                          SizedBox(
                            width: 3.w,
                          ),
                          Text(
                            '在线',
                            style:
                                TextStyle(color: Colors.white, fontSize: 8.sp),
                          )
                        ],
                      ),
                    ))
                : Positioned(
                    bottom: 0,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Color(0xFFA5A5A5),
                          borderRadius: BorderRadius.circular(10.r)),
                      padding: EdgeInsets.fromLTRB(10.w, 1.h, 10.w, 1.h),
                      child: Row(
                        children: [
                          Image.asset(
                            Constant.IMG_BASE + 'off_line.png',
                            width: 8.w,
                            height: 8.w,
                          ),
                          SizedBox(
                            width: 3.w,
                          ),
                          Text(
                            '休息',
                            style:
                                TextStyle(color: Colors.white, fontSize: 8.sp),
                          )
                        ],
                      ),
                    )),
          ],
        ));
  }

  Widget _msgItem() {
    return Container(
      padding: EdgeInsets.only(left: 24.w, top: 25.h, right: 24.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 6.w,
                    height: 6.h,
                    decoration: BoxDecoration(
                      color: Color(0xFFF43F50),
                      shape: BoxShape.circle,
                    ),
                  ),
                  Text(
                    '五一假期游戏限玩通知',
                    style: TextStyle(color: Color(0xFF333333), fontSize: 14.r),
                  )
                ],
              ),
              SizedBox(
                height: 7.h,
              ),
              Container(
                  width: MediaQuery.of(context).size.width - 38.w - 48.w,
                  child: Text('五一将近，伴随着假期的调休，发发肥肥 的火啊啊啊啊啊',
                      style:
                          TextStyle(color: Color(0xFF333333), fontSize: 14.r),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis))
            ],
          ),
          Image.asset(
            Constant.IMG_BASE + 'msg_arrow_right.png',
            width: 6.w,
            height: 11.h,
          )
        ],
      ),
    );
  }
}
